package com.cans.lightning.business.pms.service.impl;

import com.cans.lightning.base.mapper.IBaseMapper;
import com.cans.lightning.base.service.impl.BaseServiceImpl;
import com.cans.lightning.business.core.constant.Constants;
import com.cans.lightning.business.pms.dao.SysUserDao;
import com.cans.lightning.business.pms.dto.SysUserDto;
import com.cans.lightning.business.pms.entity.SysUser;
import com.cans.lightning.business.pms.mapper.SysUserMapper;
import com.cans.lightning.business.pms.service.api.ISysRoleService;
import com.cans.lightning.business.pms.service.api.ISysUserService;
import com.cans.lightning.config.redis.RedisCache;
import com.cans.lightning.utils.StringUtils;
import org.beetl.sql.core.page.PageRequest;
import org.beetl.sql.core.page.PageResult;
import org.beetl.sql.mapper.BaseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 人员操作服务
 *
 * @author shencan
 * @date 2020/6/14 20:53
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysUserServiceImpl extends BaseServiceImpl<SysUser,SysUserDto, String> implements ISysUserService {

    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ISysRoleService sysRoleService;
    @Autowired
    private RedisCache redisCache;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;


    @Override
    public BaseMapper<SysUser> getDaoImpl() {
        return sysUserDao;
    }

    @Override
    public IBaseMapper<SysUser, SysUserDto, String> getMapperImpl() {
        return sysUserMapper;
    }


    @Override
    public List<SysUser> findAll() {
        return super.findAll();
    }

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {
        return this.sysUserDao.createLambdaQuery().andEq(SysUser::getUsername,usernameOrEmail).single();
    }

    @Override
    public SysUser getByUsername(String username) {
        return this.sysUserDao.createLambdaQuery().andEq(SysUser::getUsername,username).single();
    }

    @Override
    public SysUser getByEmail(String email) {

        return this.sysUserDao.createLambdaQuery().andEq(SysUser::getEmail,email).single();
    }

    @Override
    public SysUser getCurrentUser() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SysUserDto) {
            SysUserDto sysUser = (SysUserDto) authentication.getPrincipal();
            return this.getById(sysUser.getId());
        }

        return null;
    }

    @Override
    public SysUserDto updateInfo(SysUserDto userDto) {

        SysUser user = this.getById(userDto.getId());
        // 性别
        user.setSex(userDto.getSex());
        // 年龄
        user.setAge(userDto.getAge());
        // 昵称
        user.setNickname(userDto.getNickname());
        // 电话
        user.setPhoneNum(userDto.getPhoneNum());
        // 邮箱
        user.setEmail(userDto.getEmail());
        // 简介
        user.setMemo(userDto.getMemo());
        // 头像
        if (!StringUtils.isEmpty(userDto.getAvatarId())) {
            user.setAvatarId(userDto.getAvatarId());
        }
        // 状态
        user.setStatus(userDto.getStatus());

        this.saveOrUpdate(user);

        return this.toDto(user);
    }

    @Override
    public SysUserDto toDto(SysUser user) {
        return new SysUserDto().create(user);
    }

    @Override
    public void resetPassword(String email, String password, String code) {
        String key = Constants.EMAIL_RESET_CODE + email;
        Object value = redisCache.getCacheObject(key);
        if(!code.equals(value)){
            throw new RuntimeException("验证码不匹配或已过期");
        }
        SysUser sysUser = this.getByEmail(email);
        sysUser.setPassword(passwordEncoder.encode(password));
        this.saveOrUpdate(sysUser);
    }

    @Override
    public PageResult findPage(PageRequest pageRequest) {
        return this.sysUserDao.createLambdaQuery().page(pageRequest);
    }
}
